package cn.reone.mbt.ui;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ListViewCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.reone.mbt.R;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class ScanBleActivity extends AppCompatActivity {

    @BindView(R.id.scan_device_list)
    ListViewCompat scanDeviceList;
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayList<BluetoothDevice> pairedDevices = new ArrayList<>();
    private DeviceAdapter deviceAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        ButterKnife.bind(this);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        deviceAdapter = new DeviceAdapter(pairedDevices, this);
        scanDeviceList.setAdapter(deviceAdapter);

        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

        scanDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = deviceAdapter.getItem(position);
                try {
                    BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(device.getAddress());
                    Logger.d(remoteDevice.equals(device));
                    Boolean returnValue = false;
                    if (remoteDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                        //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
                        Method createBondMethod =BluetoothDevice.class.getMethod("createBond");
                        Logger.d("BlueToothTestActivity", "开始配对");
                        returnValue = (Boolean) createBondMethod.invoke(remoteDevice);
                    }
                    if(!returnValue){
                        talk("绑定失败"+
                                (device.getBondState()==BluetoothDevice.BOND_BONDED?"设备已绑定"
                                        :" state = " + device.getBondState()));
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBluetoothLeScanner.stopScan(mScanCallback);
    }

    /**
     * Toast
     *
     * @param str
     */
    private void talk(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        Logger.d(str);
    }

    @OnClick(R.id.scan_agin)
    public void scanAgin() {
        if (mBluetoothLeScanner == null) return;
        deviceAdapter.clear();
        mBluetoothLeScanner.stopScan(mScanCallback);
        mBluetoothLeScanner.startScan(mScanCallback);
        new Thread(){
            @Override
            public void run() {
                try {
                    sleep(120000);
                    if(mBluetoothLeScanner!=null && mScanCallback!=null){
                        mBluetoothLeScanner.stopScan(mScanCallback);
                        if(ScanBleActivity.this!=null && !ScanBleActivity.this.isDestroyed()){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    talk("结束扫描");
                                }
                            });
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device = result.getDevice();
            Logger.d("扫描到结果 callbackType = " + callbackType + "\nname = " + device.getName()
                    +"\naddress = " + device.getAddress());
            if(!deviceAdapter.getPairedDevices().contains(device)){
                deviceAdapter.add(result.getDevice());
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            talk("扫描到 "+results.size()+" 条设备");
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            talk("扫描失败 code "+errorCode);
        }
    };

}
